package cn.jtool.dig.server.comm;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cn.jtool.dig.common.model.Packet;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 外部接入数据暂存区
 * 在链路通道还未创建完成的时候,外部区域上报的数据暂时存放于此
 */
@Slf4j
public class StageManager {

    private static Map<Long, List<Packet>> stages = Maps.newConcurrentMap();

    public static void addStage(long sessionId, Packet packet){
        List<Packet> packets = stages.get(sessionId);
        if(Objects.isNull(packets)){
            packets = Lists.newArrayList();
        }
        packets.add(packet);
        stages.put(sessionId, packets);
    }

    public static Map<Long, List<Packet>> getStage(){
        return stages;
    }

    public static List<Packet> getStage(long sessionId){
        return stages.get(sessionId);
    }

    public static List<Packet> getStageAndRemove(long sessionId){
        return stages.remove(sessionId);
    }

    public static Map<String, String> status(){
        Map<String, String> status = Maps.newConcurrentMap();
        status.put("number", String.valueOf(status.size()));
        Map<Long, List<Packet>> stages = StageManager.stages;
        AtomicLong size = new AtomicLong(0);
        stages.forEach((k, v) -> {
            Integer sum = v.stream().map(e -> e.encoder().length).reduce(Integer::sum).orElse(0);
            size.addAndGet(sum);
        });
        status.put("size", String.valueOf(size.get()));
        return status;
    }

    public static void removeStage(long sessionId){
        stages.remove(sessionId);
    }
}
